package org.sws.trigger.listener;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.sws.domain.behavior.event.SendRebateMessageEvent;
import org.sws.domain.behavior.strategy.context.RebateContext;
import org.sws.types.enums.ResponseCode;
import org.sws.types.event.BaseEvent;
import org.sws.types.exception.AppException;

import javax.annotation.Resource;

/**
 * @Author sws
 * @Date 2025/3/27 15:26
 * @description: 用户行为记录mq 消费
 */
@Slf4j
@Component
public class BehaviorRabateCustomer {
    @Value("${spring.rabbitmq.topic.send_rebate}")
    private String topic;
    @Resource
    private RebateContext rabateContext;

    @RabbitListener(queuesToDeclare = @Queue("${spring.rabbitmq.topic.send_rebate}"))
    public void listener(String message){
        try {
            log.info("监听用户行为消息 topic: {} message: {}", topic, message);
            // 1. 转换消息
            BaseEvent.EventMessage<SendRebateMessageEvent.RebateMessage> eventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<SendRebateMessageEvent.RebateMessage>>() {
            }.getType());
            SendRebateMessageEvent.RebateMessage rebateMessage = eventMessage.getData();
            String resultOrderId = rabateContext.executeRebate(rebateMessage.getRebateType(), rebateMessage);
            log.info("监听用户行为消息 消费成功。topic: {} message: {} resultOrderId: {}", topic, rebateMessage, resultOrderId);
        } catch (AppException e) {
            if (ResponseCode.INDEX_DUP.getCode().equals(e.getCode())) {
                log.warn("监听用户行为消息，消费重复 topic: {} message: {}", topic, message, e);
                return;
            }
            throw e;
        } catch (Exception e) {
            log.error("监听用户行为消息，消费失败 topic: {} message: {}", topic, message, e);
            throw e;
        }

    }
}
